package com.alibaba.datax.core.transport.transformer;

import com.alibaba.datax.common.element.Column;
import com.alibaba.datax.common.element.Record;
import com.alibaba.datax.common.element.StringColumn;
import com.alibaba.datax.common.exception.DataXException;
import com.alibaba.datax.core.transport.EncryptTypeEnum;
import com.alibaba.datax.core.util.SM4Utils;
import com.alibaba.datax.transformer.Transformer;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

public class EncryptTransformer extends Transformer {

    public EncryptTransformer() {
        super.setTransformerName("dx_sm4_decrypt");
    }


    @Override
    public Record evaluate(Record record, Object... paras) {

        int columnIndex;// 字段下标
        String encryptKey;// 加密key
        String encryptType;// 加密类型

        // 判断参数个数是否为3
        if (paras.length != 3) {
            throw DataXException.asDataXException(TransformerErrorCode.TRANSFORMER_ILLEGAL_PARAMETER, "paras:" + Arrays.asList(paras).toString());
        }

        columnIndex = (Integer) paras[0];
        encryptType = (String) paras[1];
        encryptKey = (String) paras[2];

        // 判断加密类型
        if (!EncryptTypeEnum.checkEncryptType(encryptType)) {
            throw DataXException.asDataXException(TransformerErrorCode.TRANSFORMER_ILLEGAL_PARAMETER, "加密类型错误->paras:" + Arrays.asList(paras).toString());
        }

        // 解密
        Column column = record.getColumn(columnIndex);
        try {
            String oriValue = column.asString();
            //如果字段为空，跳过，不进行解密操作
            if (StringUtils.isBlank(oriValue)) {
                return record;
            }

            System.out.println("开始解密" + oriValue);
            String encryptValue = "error";
            encryptValue = SM4Utils.decryptEcb(encryptKey, oriValue);
            System.out.println("结束解密" + encryptValue);

//            if (EncryptTypeEnum.AES.toString().equals(encryptType)) {
//                encryptValue = AESUtils.encrypt(oriValue, encryptKey);
//            } else if (EncryptTypeEnum.SM4.toString().equals(encryptType)) {
//            } else if (EncryptTypeEnum.MD5.toString().equals(encryptType)) {
//                encryptValue = MD5Utils.encrypt(oriValue, encryptKey);
//            } else if (EncryptTypeEnum.RSA.toString().equals(encryptType)) {
//                encryptValue = RSAUtils.encrypt(oriValue, encryptKey);
//            }

            record.setColumn(columnIndex, new StringColumn(encryptValue));
        } catch (Exception e) {
            throw DataXException.asDataXException(TransformerErrorCode.TRANSFORMER_RUN_EXCEPTION, e.getMessage(), e);
        }

        return record;
    }
}
